package cn.kgc.shiro03.controller;

import cn.kgc.shiro03.entity.User;
import cn.kgc.shiro03.service.UserService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/7/28
 * @Description:
 */

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate  stringRedisTemplate;

    @GetMapping("login")
    public Map<String ,Object> login(String username, String password, String captcha, HttpSession session){

        HashMap<String, Object> map = new HashMap<>();
        // 判定验证码是否正确  从redis中获取验证码是否正确
        String code = stringRedisTemplate.opsForValue().get(session.getId());
        if (StringUtils.isEmpty(code)){
            map.put("code",500);
            map.put("msg","验证码已失效!!!");
            return  map;
        }

        if(!code.equals(captcha)){
            map.put("code",500);
            map.put("msg","验证码错误");
            return  map;
        }

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(usernamePasswordToken);

        map.put("code",200);
        map.put("msg","登录成功");
        return  map;
    }

    @GetMapping
    public List<User> getList(){
        return userService.list();
    }


    @RequestMapping("delete")
    @RequiresRoles("admin")  //  访问当前接口 必须要有admin的角色
    public Map<String,Object> delete(Integer id){
        HashMap<String, Object> map = new HashMap<>();

        userService.removeById(id);
        map.put("code",200);
        map.put("msg","删除成功");
        return map;
    }

    @RequestMapping("register")
    public Map<String,Object> register(String username, String password){

        return userService.register(username,password);
    }


}
